<?php
namespace app\services;

use think\Db;

class UrlShortApi
{

	public $submitTimes = 0;

	protected $redis;
	protected $cid;
	protected $cidKey;
	
	public function __construct($cid = '')
    {
    	$this->cid = $cid;
    	$this->cidKey = db('bus_channel_key')->where('cid',$cid)->value('cid_key');

		$redis = new \Redis();
	    $redis->connect(config('DL_REDIS_CONFIG')['IP'], config('DL_REDIS_CONFIG')['PORT']);
	    $redis->auth(config('DL_REDIS_CONFIG')['PASSWORD']); //密码->cache(60*60*72)
	    $redis->select(2);

	    $this->redis = $redis;

   		
	    $submitTimes = $this->redis->get($cid);
   		if($submitTimes){
   			$this->submitTimes = $submitTimes;
   		}
   		
    }

    public function getSubmitTimes()
    {
    	$submitTimes = $this->redis->get($this->cid);

    	if($submitTimes){
   			$this->submitTimes = $submitTimes;
   		}else{
   			$this->submitTimes = 0;
   		}

   		return $this->submitTimes;
    }

    public function getPURedis()
    {
    	$redis = new \Redis();
	    $redis->connect(config('DL_REDIS_CONFIG')['IP'], config('DL_REDIS_CONFIG')['PORT']);
	    $redis->auth(config('DL_REDIS_CONFIG')['PASSWORD']); //密码->cache(60*60*72)
	    $redis->select(1);

    	return $redis;
    }
	/**
	 * 生成短连接
	 * @Author    lf
	 * @DateTime  2020-07-22T17:07:35+0800
	 * @copyright [copyright]
	 * @license   [license]
	 * @version   [version]
	 * @param     [type]                   $res [description]
	 */
	public function add($res)
	{
		if($this->getSubmitTimes() >= 1000){
			return['code' => 100, 'msg' => '次数达标'];
		}

		$url = 'http://47.106.66.254:80/api/short';

		$timestamp = time();


		//签名timestamp> url> cid> key(企业密钥)
		$token = md5($timestamp.$res['longUrl'].$this->cid.$this->cidKey);

		$postData = [
			'cid'       => $this->cid,
			'token'     => $token,
			'url'       => $res['longUrl'],
			'timestamp' => strval($timestamp)
		];

		if($res['day']){
			$postData['day'] = (int)$res['day'];
		}

		trace($postData);
		trace($timestamp.$res['longUrl'].strval($this->cid).$this->cidKey);

		$result = curl_post($url, $postData);trace($result);
		trace(json_encode($postData,JSON_UNESCAPED_SLASHES));
		// $ch = curl_init();
	 //    curl_setopt($ch, CURLOPT_URL, $url);
	 //    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	 //    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	 //    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	 //    // post数据
	 //    curl_setopt($ch, CURLOPT_POST, 1);
	 //    // post的变量
	 //    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
	    
	 //    curl_setopt($ch, CURLOPT_HEADER, 0);
	 //    //设置头部信息
	 //    $headers = array('Content-Type:application/json; charset=utf-8');
	 //    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	 //    //获得请求信息
	 //    curl_setopt($ch,CURLINFO_HEADER_OUT,true);

	 //    //执行请求
	 //    $output = curl_exec($ch);trace($output);
	 //    trace(curl_getinfo($ch,CURLINFO_HEADER_OUT));
	 //    //打印获得的数据
	 //    curl_close($ch);

		return $result;
	}


}